/*
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 *
 * @Author: ls
 * @Date: 2021-03-11 13:52:33
 * @LastEditTime: 2021-03-12 16:24:23
 * @LastEditors: Please set LastEditors
 * @Description: 多语言精灵帧
 * @FilePath: \creator_i18n\assets\Script\i18n\i18nSprite.ts
 */

import { i18nMgr } from './i18nMgr';
const { ccclass, property, executeInEditMode, disallowMultiple, requireComponent, menu } = cc._decorator;

@ccclass
@disallowMultiple
@executeInEditMode
@menu('多语言/i18nSprite')
@requireComponent(cc.Sprite)
export class i18nSprite extends cc.Component {
    @property({ visible: false })
    private i18n_string: string = '';
    @property({ type: cc.String, tooltip: '关键字' })
    get string() {
        return this.i18n_string;
    }
    set string(value: string) {
        this.i18n_string = value;
        this._setSprite();
    }

    start() {
        i18nMgr._addOrDelSprite(this, true);
        this.resetValue();
    }

    onDestroy() {
        i18nMgr._addOrDelSprite(this, false);
    }

    /**
     * 初始化
     * @param string 关键字
     */
    public init(string: string) {
        this.i18n_string = string;
        this._setSprite();
    }

    /**
     * 刷新精灵帧
     */
    resetValue() {
        this.string = this.i18n_string;
    }

    /**
     * 设置精灵帧
     */
    private _setSprite() {
        let sprite = this.getComponent(cc.Sprite);
        if (cc.isValid(sprite)) {
            i18nMgr._getSprite(this.i18n_string, (spriteFrame) => {
                sprite.spriteFrame = spriteFrame;
            });
        }
    }
}
